# -*- coding: utf-8 -*-
import os
import sys
import jinja2
import pytz, time
import datetime
import openerp
import simplejson
import werkzeug.utils
from openerp import http
from openerp.http import request
from openerp.osv import fields, osv
from openerp.addons.website_mshop.pools import ModelPool, CursorProxy, common_functions, PageProxy, _slug

ISODATEFORMAT = '%Y-%m-%d'
ISODATETIMEFORMAT = "%Y-%m-%d %H:%M:%S"
SUPERUSER_ID = 1

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_weixin', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)


class SaleOrderController(http.Controller):
    def __init__(self):
        env.globals['_pool'] = ModelPool()
        env.globals['_cr'] = CursorProxy()
        env.globals['_page'] = PageProxy()
        env.globals['_slug'] = _slug
        env.globals.update(common_functions)
        env.filters['tojson'] = simplejson.dumps

    @http.route(['/wx/sale/order/<int:order_id>'], auth='weixin', )
    def add_work_overtime_leave(self, order_id, **args):
        """销售 打印出入库单 自己领货出库 目前仅限于卡券订单（没有强制限制）"""
        cr, context, pool, uid = request.cr, request.context, request.registry, request.session.uid
        if args.get('id'):
            cr.execute("""""")
        else:
            kw = {'user_name': "系统管理员", 'user_id': 1}

        order_id = pool['sale.order'].search(cr, uid, [('id', '=', order_id)], context=context)
        if order_id:
            try:
                order_row = pool['sale.order'].browse(cr, uid, order_id, context=context)
                order_line = [{'product_name': line.name,
                               'product_code': line.product_id.default_code,
                               'product_uom_qty': line.product_uom_qty,
                               'price_unit': line.price_unit,
                               'price_subtotal': line.price_subtotal,
                               }
                              for line in order_row.order_line]
                order_dict = {
                    'name': order_row.name,
                    'partner_name': order_row.partner_id.name,
                    'is_card': order_row.is_card,
                    'expected_delivery_time': order_row.expected_delivery_time,
                    #'sale_order_invoice': order_row.sale_order_invoice,
                    'print_state': order_row.print_state,
                    'shipment_completion': order_row.shipment_completion,
                    'purchase_managed': order_row.purchase_managed,
                    'payment_method': order_row.payment_method,
                    'order_line': order_line,
                    'amount_total': order_row.amount_total,
                    'inner_note': order_row.inner_note,
                    'stock_note': order_row.stock_note,
                    'note': order_row.note,
                    'order_id': order_row.id,
                    'state': order_row.state,
                    'error': False,
                }
            except Exception as error_message:
                order_dict = {
                    'error': True,
                    'error_message': "%s" % error_message[1]
                }
        else:
            order_dict = {
                'error': True,
                'error_message': "%s" % ('您没有读取订单的权限')
            }

        template = env.get_template("sale/sale.html")
        kw.update({'order': simplejson.dumps(order_dict)})
        return template.render(kw)